# -*- coding: utf-8 -*-

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import datetime  # For datetime objects
import pandas as pd
import backtrader as bt

class SignalDemo(bt.Indicator):
  lines = ('signal',)
  params = (('period', 5),)

  def __init__(self):
    self.lines.signal = self.data - bt.indicators.SMA(period=self.p.period)

if __name__ == '__main__':
  cerebro = bt.Cerebro()
  dataframe = pd.read_csv("../analysis/000921.csv", index_col = 'trade_date', parse_dates = True)
  dataframe.rename(columns={'vol':'volume'}, inplace = True)
  dataframe['openinterest'] = 0
  data = bt.feeds.PandasData(dataname=dataframe)
  # Add the Data Feed to Cerebro
  cerebro.adddata(data)

  cerebro.add_signal(bt.SIGNAL_LONGSHORT, SignalDemo, subplot=False)
  # 这句话很有用，画图看效果
  # cerebro.signal_accumulate(True)
  cerebro.broker.setcash(10000.0)
  cerebro.addsizer(bt.sizers.FixedSize, stake=10)
  cerebro.broker.setcommission(commission=0.0)
  print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
  cerebro.run()
  print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
  cerebro.plot()
  cerebro.signal_accumulate(True)